#include <PubSubClient.h>
#include "conf.h"

#define retained_0 false
#define retained_1 true

#define Hass_Mqtt_name "MCH_ESP_%s_%s"

/*Home Assistant Auto Discover config*/
#define MQTT_CONFIG_TOPIC_TEMPLATE  "homeassistant/switch/%s/config"
#define MQTT_AUTO_DISCOVER "homeassistant/switch/%s"
#define MQTT_STATE_TOPIC_TEMPLATE   MQTT_AUTO_DISCOVER"/state"
#define MQTT_COMMAND_TOPIC_TEMPLATE MQTT_AUTO_DISCOVER"/set"

class Light
{
private:
    uint8_t pin;

public:
    bool state;
    bool changed;
    Light(uint8_t pin);
    void on();
    void off();
    void toggle();
};

class HaSwitch
{
private:
    /* data */
    char* Id;
    PubSubClient* mqttclient;
    char* config_text;
    char* state_topic;
    char* config_topic;
    char jsonBuffer[256] = {0};
    char MQTT_CLIENT_ID[7] = {0};
    char NAME[sizeof(Hass_Mqtt_name) + sizeof(MQTT_CLIENT_ID) + 2 - 4] = {0};
    char MQTT_CONFIG_TOPIC[sizeof(MQTT_CONFIG_TOPIC_TEMPLATE) + sizeof(NAME) - 2] = {0};
    char MQTT_STATE_TOPIC[sizeof(MQTT_STATE_TOPIC_TEMPLATE) + sizeof(NAME) - 2] = {0};
    char MQTT_COMMAND_TOPIC[sizeof(MQTT_COMMAND_TOPIC_TEMPLATE) + sizeof(NAME) - 2] = {0};

public:
    Light *light;
    char* cmd_topic;

    HaSwitch(Light *light, const char *index, PubSubClient *Client);
    void send_state();
    void begin();
    void handle();
};

class HassMqtt : public PubSubClient
{
public:
    using PubSubClient::PubSubClient;
    char MQTT_CLIENT_ID[7] = {0};

    char mqtt_server[30] = {0};
    char Hass_Mqtt_user[30] = {0};
    char Hass_Mqtt_pass[30] = {0};
    uint16_t Hass_Mqtt_port;

    void begin();
    void keybegin();
    void keyhandle();
    void handle();
    void reconnect();
};
